<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Addons | Node.js v6.9.4 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/sh.css">
  <link rel="canonical" href="https://nodejs.org/api/addons.html">
</head>
<body class="alt apidoc" id="api-section-addons">
  <div id="content" class="clearfix">
    <div id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Usage &amp; Example</a></li>
</ul>
<div class="line"></div>

<ul>
<li><a class="nav-assert" href="assert.html">Assertion Testing</a></li>
<li><a class="nav-buffer" href="buffer.html">Buffer</a></li>
<li><a class="nav-addons active" href="addons.html">C/C++ Addons</a></li>
<li><a class="nav-child_process" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster" href="cluster.html">Cluster</a></li>
<li><a class="nav-cli" href="cli.html">Command Line Options</a></li>
<li><a class="nav-console" href="console.html">Console</a></li>
<li><a class="nav-crypto" href="crypto.html">Crypto</a></li>
<li><a class="nav-debugger" href="debugger.html">Debugger</a></li>
<li><a class="nav-dns" href="dns.html">DNS</a></li>
<li><a class="nav-domain" href="domain.html">Domain</a></li>
<li><a class="nav-errors" href="errors.html">Errors</a></li>
<li><a class="nav-events" href="events.html">Events</a></li>
<li><a class="nav-fs" href="fs.html">File System</a></li>
<li><a class="nav-globals" href="globals.html">Globals</a></li>
<li><a class="nav-http" href="http.html">HTTP</a></li>
<li><a class="nav-https" href="https.html">HTTPS</a></li>
<li><a class="nav-modules" href="modules.html">Modules</a></li>
<li><a class="nav-net" href="net.html">Net</a></li>
<li><a class="nav-os" href="os.html">OS</a></li>
<li><a class="nav-path" href="path.html">Path</a></li>
<li><a class="nav-process" href="process.html">Process</a></li>
<li><a class="nav-punycode" href="punycode.html">Punycode</a></li>
<li><a class="nav-querystring" href="querystring.html">Query Strings</a></li>
<li><a class="nav-readline" href="readline.html">Readline</a></li>
<li><a class="nav-repl" href="repl.html">REPL</a></li>
<li><a class="nav-stream" href="stream.html">Stream</a></li>
<li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li>
<li><a class="nav-timers" href="timers.html">Timers</a></li>
<li><a class="nav-tls" href="tls.html">TLS/SSL</a></li>
<li><a class="nav-tty" href="tty.html">TTY</a></li>
<li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li>
<li><a class="nav-url" href="url.html">URL</a></li>
<li><a class="nav-util" href="util.html">Utilities</a></li>
<li><a class="nav-v8" href="v8.html">V8</a></li>
<li><a class="nav-vm" href="vm.html">VM</a></li>
<li><a class="nav-zlib" href="zlib.html">ZLIB</a></li>
</ul>
<div class="line"></div>

<ul>
<li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo &amp; Issue Tracker</a></li>
<li><a class="nav-http-groups-google-com-group-nodejs" href="http://groups.google.com/group/nodejs">Mailing List</a></li>
</ul>

    </div>

    <div id="column1" data-id="addons" class="interior">
      <header>
        <h1>Node.js v6.9.4 Documentation</h1>
        <div id="gtoc">
          <p>
            <a href="index.html" name="toc">Index</a> |
            <a href="all.html">View on single page</a> |
            <a href="addons.json">View as JSON</a>
          </p>
        </div>
        <hr>
      </header>

      <div id="toc">
        <h2>Table of Contents</h2>
        <ul>
<li><span class="stability_undefined"><a href="#addons_addons">Addons</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_hello_world">Hello world</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_building">Building</a></span></li>
<li><span class="stability_undefined"><a href="#addons_linking_to_node_js_own_dependencies">Linking to Node.js&#39; own dependencies</a></span></li>
<li><span class="stability_undefined"><a href="#addons_loading_addons_using_require">Loading Addons using require()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#addons_native_abstractions_for_node_js">Native Abstractions for Node.js</a></span></li>
<li><span class="stability_undefined"><a href="#addons_addon_examples">Addon examples</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_function_arguments">Function arguments</a></span></li>
<li><span class="stability_undefined"><a href="#addons_callbacks">Callbacks</a></span></li>
<li><span class="stability_undefined"><a href="#addons_object_factory">Object factory</a></span></li>
<li><span class="stability_undefined"><a href="#addons_function_factory">Function factory</a></span></li>
<li><span class="stability_undefined"><a href="#addons_wrapping_c_objects">Wrapping C++ objects</a></span></li>
<li><span class="stability_undefined"><a href="#addons_factory_of_wrapped_objects">Factory of wrapped objects</a></span></li>
<li><span class="stability_undefined"><a href="#addons_passing_wrapped_objects_around">Passing wrapped objects around</a></span></li>
<li><span class="stability_undefined"><a href="#addons_atexit_hooks">AtExit hooks</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_void_atexit_callback_args">void AtExit(callback, args)</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

      </div>

      <div id="apicontent">
        <h1>Addons<span><a class="mark" href="#addons_addons" id="addons_addons">#</a></span></h1>
<p>Node.js Addons are dynamically-linked shared objects, written in C or C++, that
can be loaded into Node.js using the <a href="globals.html#globals_require"><code>require()</code></a> function, and used
just as if they were an ordinary Node.js module. They are used primarily to
provide an interface between JavaScript running in Node.js and C/C++ libraries.</p>
<p>At the moment, the method for implementing Addons is rather complicated,
involving knowledge of several components and APIs :</p>
<ul>
<li><p>V8: the C++ library Node.js currently uses to provide the
JavaScript implementation. V8 provides the mechanisms for creating objects,
calling functions, etc. V8&#39;s API is documented mostly in the
<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node.js source
tree), which is also available <a href="https://v8docs.nodesource.com/">online</a>.</p>
</li>
<li><p><a href="https://github.com/libuv/libuv">libuv</a>: The C library that implements the Node.js event loop, its worker
threads and all of the asynchronous behaviors of the platform. It also
serves as a cross-platform abstraction library, giving easy, POSIX-like
access across all major operating systems to many common system tasks, such
as interacting with the filesystem, sockets, timers and system events. libuv
also provides a pthreads-like threading abstraction that may be used to
power more sophisticated asynchronous Addons that need to move beyond the
standard event loop. Addon authors are encouraged to think about how to
avoid blocking the event loop with I/O or other time-intensive tasks by
off-loading work via libuv to non-blocking system operations, worker threads
or a custom use of libuv&#39;s threads.</p>
</li>
<li><p>Internal Node.js libraries. Node.js itself exports a number of C/C++ APIs
that Addons can use &mdash; the most important of which is the
<code>node::ObjectWrap</code> class.</p>
</li>
<li><p>Node.js includes a number of other statically linked libraries including
OpenSSL. These other libraries are located in the <code>deps/</code> directory in the
Node.js source tree. Only the V8 and OpenSSL symbols are purposefully
re-exported by Node.js and may be used to various extents by Addons.
See <a href="#addons_linking_to_node_js_own_dependencies">Linking to Node.js&#39; own dependencies</a> for additional information.</p>
</li>
</ul>
<p>All of the following examples are available for <a href="https://github.com/nodejs/node-addon-examples">download</a> and may
be used as a starting-point for your own Addon.</p>
<h2>Hello world<span><a class="mark" href="#addons_hello_world" id="addons_hello_world">#</a></span></h2>
<p>This &quot;Hello world&quot; example is a simple Addon, written in C++, that is the
equivalent of the following JavaScript code:</p>
<pre><code class="lang-js">module.exports.hello = () =&gt; &#39;world&#39;;
</code></pre>
<p>First, create the file <code>hello.cc</code>:</p>
<pre><code class="lang-cpp">// hello.cc
#include &lt;node.h&gt;

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, &quot;world&quot;));
}

void init(Local&lt;Object&gt; exports) {
  NODE_SET_METHOD(exports, &quot;hello&quot;, Method);
}

NODE_MODULE(addon, init)

}  // namespace demo
</code></pre>
<p>Note that all Node.js Addons must export an initialization function following
the pattern:</p>
<pre><code class="lang-cpp">void Initialize(Local&lt;Object&gt; exports);
NODE_MODULE(module_name, Initialize)
</code></pre>
<p>There is no semi-colon after <code>NODE_MODULE</code> as it&#39;s not a function (see
<code>node.h</code>).</p>
<p>The <code>module_name</code> must match the filename of the final binary (excluding
the .node suffix).</p>
<p>In the <code>hello.cc</code> example, then, the initialization function is <code>init</code> and the
Addon module name is <code>addon</code>.</p>
<h3>Building<span><a class="mark" href="#addons_building" id="addons_building">#</a></span></h3>
<p>Once the source code has been written, it must be compiled into the binary
<code>addon.node</code> file. To do so, create a file called <code>binding.gyp</code> in the
top-level of the project describing the build configuration of your module
using a JSON-like format. This file is used by <a href="https://github.com/nodejs/node-gyp">node-gyp</a> -- a tool written
specifically to compile Node.js Addons.</p>
<pre><code class="lang-json">{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;addon&quot;,
      &quot;sources&quot;: [ &quot;hello.cc&quot; ]
    }
  ]
}
</code></pre>
<p><em>Note: A version of the <code>node-gyp</code> utility is bundled and distributed with
Node.js as part of <code>npm</code>. This version is not made directly available for
developers to use and is intended only to support the ability to use the
<code>npm install</code> command to compile and install Addons. Developers who wish to
use <code>node-gyp</code> directly can install it using the command
<code>npm install -g node-gyp</code>. See the <code>node-gyp</code> <a href="https://github.com/nodejs/node-gyp#installation">installation instructions</a> for
more information, including platform-specific requirements.</em></p>
<p>Once the <code>binding.gyp</code> file has been created, use <code>node-gyp configure</code> to
generate the appropriate project build files for the current platform. This
will generate either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file
(on Windows) in the <code>build/</code> directory.</p>
<p>Next, invoke the <code>node-gyp build</code> command to generate the compiled <code>addon.node</code>
file. This will be put into the <code>build/Release/</code> directory.</p>
<p>When using <code>npm install</code> to install a Node.js Addon, npm uses its own bundled
version of <code>node-gyp</code> to perform this same set of actions, generating a
compiled version of the Addon for the user&#39;s platform on demand.</p>
<p>Once built, the binary Addon can be used from within Node.js by pointing
<a href="globals.html#globals_require"><code>require()</code></a> to the built <code>addon.node</code> module:</p>
<pre><code class="lang-js">// hello.js
const addon = require(&#39;./build/Release/addon&#39;);

console.log(addon.hello());
// Prints: &#39;world&#39;
</code></pre>
<p>Please see the examples below for further information or
<a href="https://github.com/arturadib/node-qt">https://github.com/arturadib/node-qt</a> for an example in production.</p>
<p>Because the exact path to the compiled Addon binary can vary depending on how
it is compiled (i.e. sometimes it may be in <code>./build/Debug/</code>), Addons can use
the <a href="https://github.com/TooTallNate/node-bindings">bindings</a> package to load the compiled module.</p>
<p>Note that while the <code>bindings</code> package implementation is more sophisticated
in how it locates Addon modules, it is essentially using a try-catch pattern
similar to:</p>
<pre><code class="lang-js">try {
  return require(&#39;./build/Release/addon.node&#39;);
} catch (err) {
  return require(&#39;./build/Debug/addon.node&#39;);
}
</code></pre>
<h3>Linking to Node.js&#39; own dependencies<span><a class="mark" href="#addons_linking_to_node_js_own_dependencies" id="addons_linking_to_node_js_own_dependencies">#</a></span></h3>
<p>Node.js uses a number of statically linked libraries such as V8, libuv and
OpenSSL. All Addons are required to link to V8 and may link to any of the
other dependencies as well. Typically, this is as simple as including
the appropriate <code>#include &lt;...&gt;</code> statements (e.g. <code>#include &lt;v8.h&gt;</code>) and
<code>node-gyp</code> will locate the appropriate headers automatically. However, there
are a few caveats to be aware of:</p>
<ul>
<li><p>When <code>node-gyp</code> runs, it will detect the specific release version of Node.js
and download either the full source tarball or just the headers. If the full
source is downloaded, Addons will have complete access to the full set of
Node.js dependencies. However, if only the Node.js headers are downloaded, then
only the symbols exported by Node.js will be available.</p>
</li>
<li><p><code>node-gyp</code> can be run using the <code>--nodedir</code> flag pointing at a local Node.js
source image. Using this option, the Addon will have access to the full set of
dependencies.</p>
</li>
</ul>
<h3>Loading Addons using require()<span><a class="mark" href="#addons_loading_addons_using_require" id="addons_loading_addons_using_require">#</a></span></h3>
<p>The filename extension of the compiled Addon binary is <code>.node</code> (as opposed
to <code>.dll</code> or <code>.so</code>). The <a href="globals.html#globals_require"><code>require()</code></a> function is written to look for
files with the <code>.node</code> file extension and initialize those as dynamically-linked
libraries.</p>
<p>When calling <a href="globals.html#globals_require"><code>require()</code></a>, the <code>.node</code> extension can usually be
omitted and Node.js will still find and initialize the Addon. One caveat,
however, is that Node.js will first attempt to locate and load modules or
JavaScript files that happen to share the same base name. For instance, if
there is a file <code>addon.js</code> in the same directory as the binary <code>addon.node</code>,
then <a href="globals.html#globals_require"><code>require(&#39;addon&#39;)</code></a> will give precedence to the <code>addon.js</code> file
and load it instead.</p>
<h2>Native Abstractions for Node.js<span><a class="mark" href="#addons_native_abstractions_for_node_js" id="addons_native_abstractions_for_node_js">#</a></span></h2>
<p>Each of the examples illustrated in this document make direct use of the
Node.js and V8 APIs for implementing Addons. It is important to understand
that the V8 API can, and has, changed dramatically from one V8 release to the
next (and one major Node.js release to the next). With each change, Addons may
need to be updated and recompiled in order to continue functioning. The Node.js
release schedule is designed to minimize the frequency and impact of such
changes but there is little that Node.js can do currently to ensure stability
of the V8 APIs.</p>
<p>The <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> (or <code>nan</code>) provide a set of tools that
Addon developers are recommended to use to keep compatibility between past and
future releases of V8 and Node.js. See the <code>nan</code> <a href="https://github.com/nodejs/nan/tree/master/examples/">examples</a> for an
illustration of how it can be used.</p>
<h2>Addon examples<span><a class="mark" href="#addons_addon_examples" id="addons_addon_examples">#</a></span></h2>
<p>Following are some example Addons intended to help developers get started. The
examples make use of the V8 APIs. Refer to the online <a href="https://v8docs.nodesource.com/">V8 reference</a>
for help with the various V8 calls, and V8&#39;s <a href="https://developers.google.com/v8/embed">Embedder&#39;s Guide</a> for an
explanation of several concepts used such as handles, scopes, function
templates, etc.</p>
<p>Each of these examples using the following <code>binding.gyp</code> file:</p>
<pre><code class="lang-json">{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;addon&quot;,
      &quot;sources&quot;: [ &quot;addon.cc&quot; ]
    }
  ]
}
</code></pre>
<p>In cases where there is more than one <code>.cc</code> file, simply add the additional
filename to the <code>sources</code> array. For example:</p>
<pre><code class="lang-json">&quot;sources&quot;: [&quot;addon.cc&quot;, &quot;myexample.cc&quot;]
</code></pre>
<p>Once the <code>binding.gyp</code> file is ready, the example Addons can be configured and
built using <code>node-gyp</code>:</p>
<pre><code class="lang-console">$ node-gyp configure build
</code></pre>
<h3>Function arguments<span><a class="mark" href="#addons_function_arguments" id="addons_function_arguments">#</a></span></h3>
<p>Addons will typically expose objects and functions that can be accessed from
JavaScript running within Node.js. When functions are invoked from JavaScript,
the input arguments and return value must be mapped to and from the C/C++
code.</p>
<p>The following example illustrates how to read function arguments passed from
JavaScript and how to return a result:</p>
<pre><code class="lang-cpp">// addon.cc
#include &lt;node.h&gt;

namespace demo {

using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

// This is the implementation of the &quot;add&quot; method
// Input arguments are passed using the
// const FunctionCallbackInfo&lt;Value&gt;&amp; args struct
void Add(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  // Check the number of arguments passed.
  if (args.Length() &lt; 2) {
    // Throw an Error that is passed back to JavaScript
    isolate-&gt;ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, &quot;Wrong number of arguments&quot;)));
    return;
  }

  // Check the argument types
  if (!args[0]-&gt;IsNumber() || !args[1]-&gt;IsNumber()) {
    isolate-&gt;ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, &quot;Wrong arguments&quot;)));
    return;
  }

  // Perform the operation
  double value = args[0]-&gt;NumberValue() + args[1]-&gt;NumberValue();
  Local&lt;Number&gt; num = Number::New(isolate, value);

  // Set the return value (using the passed in
  // FunctionCallbackInfo&lt;Value&gt;&amp;)
  args.GetReturnValue().Set(num);
}

void Init(Local&lt;Object&gt; exports) {
  NODE_SET_METHOD(exports, &quot;add&quot;, Add);
}

NODE_MODULE(addon, Init)

}  // namespace demo
</code></pre>
<p>Once compiled, the example Addon can be required and used from within Node.js:</p>
<pre><code class="lang-js">// test.js
const addon = require(&#39;./build/Release/addon&#39;);

console.log(&#39;This should be eight:&#39;, addon.add(3, 5));
</code></pre>
<h3>Callbacks<span><a class="mark" href="#addons_callbacks" id="addons_callbacks">#</a></span></h3>
<p>It is common practice within Addons to pass JavaScript functions to a C++
function and execute them from there. The following example illustrates how
to invoke such callbacks:</p>
<pre><code class="lang-cpp">// addon.cc
#include &lt;node.h&gt;

namespace demo {

using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;

void RunCallback(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();
  Local&lt;Function&gt; cb = Local&lt;Function&gt;::Cast(args[0]);
  const unsigned argc = 1;
  Local&lt;Value&gt; argv[argc] = { String::NewFromUtf8(isolate, &quot;hello world&quot;) };
  cb-&gt;Call(Null(isolate), argc, argv);
}

void Init(Local&lt;Object&gt; exports, Local&lt;Object&gt; module) {
  NODE_SET_METHOD(module, &quot;exports&quot;, RunCallback);
}

NODE_MODULE(addon, Init)

}  // namespace demo
</code></pre>
<p>Note that this example uses a two-argument form of <code>Init()</code> that receives
the full <code>module</code> object as the second argument. This allows the Addon
to completely overwrite <code>exports</code> with a single function instead of
adding the function as a property of <code>exports</code>.</p>
<p>To test it, run the following JavaScript:</p>
<pre><code class="lang-js">// test.js
const addon = require(&#39;./build/Release/addon&#39;);

addon((msg) =&gt; {
  console.log(msg);
// Prints: &#39;hello world&#39;
});
</code></pre>
<p>Note that, in this example, the callback function is invoked synchronously.</p>
<h3>Object factory<span><a class="mark" href="#addons_object_factory" id="addons_object_factory">#</a></span></h3>
<p>Addons can create and return new objects from within a C++ function as
illustrated in the following example. An object is created and returned with a
property <code>msg</code> that echoes the string passed to <code>createObject()</code>:</p>
<pre><code class="lang-cpp">// addon.cc
#include &lt;node.h&gt;

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  Local&lt;Object&gt; obj = Object::New(isolate);
  obj-&gt;Set(String::NewFromUtf8(isolate, &quot;msg&quot;), args[0]-&gt;ToString());

  args.GetReturnValue().Set(obj);
}

void Init(Local&lt;Object&gt; exports, Local&lt;Object&gt; module) {
  NODE_SET_METHOD(module, &quot;exports&quot;, CreateObject);
}

NODE_MODULE(addon, Init)

}  // namespace demo
</code></pre>
<p>To test it in JavaScript:</p>
<pre><code class="lang-js">// test.js
const addon = require(&#39;./build/Release/addon&#39;);

const obj1 = addon(&#39;hello&#39;);
const obj2 = addon(&#39;world&#39;);
console.log(obj1.msg, obj2.msg);
// Prints: &#39;hello world&#39;
</code></pre>
<h3>Function factory<span><a class="mark" href="#addons_function_factory" id="addons_function_factory">#</a></span></h3>
<p>Another common scenario is creating JavaScript functions that wrap C++
functions and returning those back to JavaScript:</p>
<pre><code class="lang-cpp">// addon.cc
#include &lt;node.h&gt;

namespace demo {

using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void MyFunction(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, &quot;hello world&quot;));
}

void CreateFunction(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  Local&lt;FunctionTemplate&gt; tpl = FunctionTemplate::New(isolate, MyFunction);
  Local&lt;Function&gt; fn = tpl-&gt;GetFunction();

  // omit this to make it anonymous
  fn-&gt;SetName(String::NewFromUtf8(isolate, &quot;theFunction&quot;));

  args.GetReturnValue().Set(fn);
}

void Init(Local&lt;Object&gt; exports, Local&lt;Object&gt; module) {
  NODE_SET_METHOD(module, &quot;exports&quot;, CreateFunction);
}

NODE_MODULE(addon, Init)

}  // namespace demo
</code></pre>
<p>To test:</p>
<pre><code class="lang-js">// test.js
const addon = require(&#39;./build/Release/addon&#39;);

const fn = addon();
console.log(fn());
// Prints: &#39;hello world&#39;
</code></pre>
<h3>Wrapping C++ objects<span><a class="mark" href="#addons_wrapping_c_objects" id="addons_wrapping_c_objects">#</a></span></h3>
<p>It is also possible to wrap C++ objects/classes in a way that allows new
instances to be created using the JavaScript <code>new</code> operator:</p>
<pre><code class="lang-cpp">// addon.cc
#include &lt;node.h&gt;
#include &quot;myobject.h&quot;

namespace demo {

using v8::Local;
using v8::Object;

void InitAll(Local&lt;Object&gt; exports) {
  MyObject::Init(exports);
}

NODE_MODULE(addon, InitAll)

}  // namespace demo
</code></pre>
<p>Then, in <code>myobject.h</code>, the wrapper class inherits from <code>node::ObjectWrap</code>:</p>
<pre><code class="lang-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include &lt;node.h&gt;
#include &lt;node_object_wrap.h&gt;

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Local&lt;v8::Object&gt; exports);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args);
  static void PlusOne(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args);
  static v8::Persistent&lt;v8::Function&gt; constructor;
  double value_;
};

}  // namespace demo

#endif
</code></pre>
<p>In <code>myobject.cc</code>, implement the various methods that are to be exposed.
Below, the method <code>plusOne()</code> is exposed by adding it to the constructor&#39;s
prototype:</p>
<pre><code class="lang-cpp">// myobject.cc
#include &quot;myobject.h&quot;

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;

Persistent&lt;Function&gt; MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Local&lt;Object&gt; exports) {
  Isolate* isolate = exports-&gt;GetIsolate();

  // Prepare constructor template
  Local&lt;FunctionTemplate&gt; tpl = FunctionTemplate::New(isolate, New);
  tpl-&gt;SetClassName(String::NewFromUtf8(isolate, &quot;MyObject&quot;));
  tpl-&gt;InstanceTemplate()-&gt;SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, &quot;plusOne&quot;, PlusOne);

  constructor.Reset(isolate, tpl-&gt;GetFunction());
  exports-&gt;Set(String::NewFromUtf8(isolate, &quot;MyObject&quot;),
               tpl-&gt;GetFunction());
}

void MyObject::New(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]-&gt;IsUndefined() ? 0 : args[0]-&gt;NumberValue();
    MyObject* obj = new MyObject(value);
    obj-&gt;Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local&lt;Value&gt; argv[argc] = { args[0] };
    Local&lt;Context&gt; context = isolate-&gt;GetCurrentContext();
    Local&lt;Function&gt; cons = Local&lt;Function&gt;::New(isolate, constructor);
    Local&lt;Object&gt; result =
        cons-&gt;NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(result);
  }
}

void MyObject::PlusOne(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap&lt;MyObject&gt;(args.Holder());
  obj-&gt;value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj-&gt;value_));
}

}  // namespace demo
</code></pre>
<p>To build this example, the <code>myobject.cc</code> file must be added to the
<code>binding.gyp</code>:</p>
<pre><code class="lang-json">{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;addon&quot;,
      &quot;sources&quot;: [
        &quot;addon.cc&quot;,
        &quot;myobject.cc&quot;
      ]
    }
  ]
}
</code></pre>
<p>Test it with:</p>
<pre><code class="lang-js">// test.js
const addon = require(&#39;./build/Release/addon&#39;);

const obj = new addon.MyObject(10);
console.log(obj.plusOne());
// Prints: 11
console.log(obj.plusOne());
// Prints: 12
console.log(obj.plusOne());
// Prints: 13
</code></pre>
<h3>Factory of wrapped objects<span><a class="mark" href="#addons_factory_of_wrapped_objects" id="addons_factory_of_wrapped_objects">#</a></span></h3>
<p>Alternatively, it is possible to use a factory pattern to avoid explicitly
creating object instances using the JavaScript <code>new</code> operator:</p>
<pre><code class="lang-js">const obj = addon.createObject();
// instead of:
// const obj = new addon.Object();
</code></pre>
<p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p>
<pre><code class="lang-cpp">// addon.cc
#include &lt;node.h&gt;
#include &quot;myobject.h&quot;

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  MyObject::NewInstance(args);
}

void InitAll(Local&lt;Object&gt; exports, Local&lt;Object&gt; module) {
  MyObject::Init(exports-&gt;GetIsolate());

  NODE_SET_METHOD(module, &quot;exports&quot;, CreateObject);
}

NODE_MODULE(addon, InitAll)

}  // namespace demo
</code></pre>
<p>In <code>myobject.h</code>, the static method <code>NewInstance()</code> is added to handle
instantiating the object. This method takes the place of using <code>new</code> in
JavaScript:</p>
<pre><code class="lang-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include &lt;node.h&gt;
#include &lt;node_object_wrap.h&gt;

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Isolate* isolate);
  static void NewInstance(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args);
  static void PlusOne(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args);
  static v8::Persistent&lt;v8::Function&gt; constructor;
  double value_;
};

}  // namespace demo

#endif
</code></pre>
<p>The implementation in <code>myobject.cc</code> is similar to the previous example:</p>
<pre><code class="lang-cpp">// myobject.cc
#include &lt;node.h&gt;
#include &quot;myobject.h&quot;

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;

Persistent&lt;Function&gt; MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Isolate* isolate) {
  // Prepare constructor template
  Local&lt;FunctionTemplate&gt; tpl = FunctionTemplate::New(isolate, New);
  tpl-&gt;SetClassName(String::NewFromUtf8(isolate, &quot;MyObject&quot;));
  tpl-&gt;InstanceTemplate()-&gt;SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, &quot;plusOne&quot;, PlusOne);

  constructor.Reset(isolate, tpl-&gt;GetFunction());
}

void MyObject::New(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]-&gt;IsUndefined() ? 0 : args[0]-&gt;NumberValue();
    MyObject* obj = new MyObject(value);
    obj-&gt;Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local&lt;Value&gt; argv[argc] = { args[0] };
    Local&lt;Function&gt; cons = Local&lt;Function&gt;::New(isolate, constructor);
    Local&lt;Context&gt; context = isolate-&gt;GetCurrentContext();
    Local&lt;Object&gt; instance =
        cons-&gt;NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(instance);
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local&lt;Value&gt; argv[argc] = { args[0] };
  Local&lt;Function&gt; cons = Local&lt;Function&gt;::New(isolate, constructor);
  Local&lt;Context&gt; context = isolate-&gt;GetCurrentContext();
  Local&lt;Object&gt; instance =
      cons-&gt;NewInstance(context, argc, argv).ToLocalChecked();

  args.GetReturnValue().Set(instance);
}

void MyObject::PlusOne(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap&lt;MyObject&gt;(args.Holder());
  obj-&gt;value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj-&gt;value_));
}

}  // namespace demo
</code></pre>
<p>Once again, to build this example, the <code>myobject.cc</code> file must be added to the
<code>binding.gyp</code>:</p>
<pre><code class="lang-json">{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;addon&quot;,
      &quot;sources&quot;: [
        &quot;addon.cc&quot;,
        &quot;myobject.cc&quot;
      ]
    }
  ]
}
</code></pre>
<p>Test it with:</p>
<pre><code class="lang-js">// test.js
const createObject = require(&#39;./build/Release/addon&#39;);

const obj = createObject(10);
console.log(obj.plusOne());
// Prints: 11
console.log(obj.plusOne());
// Prints: 12
console.log(obj.plusOne());
// Prints: 13

const obj2 = createObject(20);
console.log(obj2.plusOne());
// Prints: 21
console.log(obj2.plusOne());
// Prints: 22
console.log(obj2.plusOne());
// Prints: 23
</code></pre>
<h3>Passing wrapped objects around<span><a class="mark" href="#addons_passing_wrapped_objects_around" id="addons_passing_wrapped_objects_around">#</a></span></h3>
<p>In addition to wrapping and returning C++ objects, it is possible to pass
wrapped objects around by unwrapping them with the Node.js helper function
<code>node::ObjectWrap::Unwrap</code>. The following examples shows a function <code>add()</code>
that can take two <code>MyObject</code> objects as input arguments:</p>
<pre><code class="lang-cpp">// addon.cc
#include &lt;node.h&gt;
#include &lt;node_object_wrap.h&gt;
#include &quot;myobject.h&quot;

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  MyObject::NewInstance(args);
}

void Add(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj1 = node::ObjectWrap::Unwrap&lt;MyObject&gt;(
      args[0]-&gt;ToObject());
  MyObject* obj2 = node::ObjectWrap::Unwrap&lt;MyObject&gt;(
      args[1]-&gt;ToObject());

  double sum = obj1-&gt;value() + obj2-&gt;value();
  args.GetReturnValue().Set(Number::New(isolate, sum));
}

void InitAll(Local&lt;Object&gt; exports) {
  MyObject::Init(exports-&gt;GetIsolate());

  NODE_SET_METHOD(exports, &quot;createObject&quot;, CreateObject);
  NODE_SET_METHOD(exports, &quot;add&quot;, Add);
}

NODE_MODULE(addon, InitAll)

}  // namespace demo
</code></pre>
<p>In <code>myobject.h</code>, a new public method is added to allow access to private values
after unwrapping the object.</p>
<pre><code class="lang-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include &lt;node.h&gt;
#include &lt;node_object_wrap.h&gt;

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Isolate* isolate);
  static void NewInstance(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args);
  inline double value() const { return value_; }

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args);
  static v8::Persistent&lt;v8::Function&gt; constructor;
  double value_;
};

}  // namespace demo

#endif
</code></pre>
<p>The implementation of <code>myobject.cc</code> is similar to before:</p>
<pre><code class="lang-cpp">// myobject.cc
#include &lt;node.h&gt;
#include &quot;myobject.h&quot;

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;

Persistent&lt;Function&gt; MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Isolate* isolate) {
  // Prepare constructor template
  Local&lt;FunctionTemplate&gt; tpl = FunctionTemplate::New(isolate, New);
  tpl-&gt;SetClassName(String::NewFromUtf8(isolate, &quot;MyObject&quot;));
  tpl-&gt;InstanceTemplate()-&gt;SetInternalFieldCount(1);

  constructor.Reset(isolate, tpl-&gt;GetFunction());
}

void MyObject::New(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]-&gt;IsUndefined() ? 0 : args[0]-&gt;NumberValue();
    MyObject* obj = new MyObject(value);
    obj-&gt;Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local&lt;Value&gt; argv[argc] = { args[0] };
    Local&lt;Context&gt; context = isolate-&gt;GetCurrentContext();
    Local&lt;Function&gt; cons = Local&lt;Function&gt;::New(isolate, constructor);
    Local&lt;Object&gt; instance =
        cons-&gt;NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(instance);
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local&lt;Value&gt; argv[argc] = { args[0] };
  Local&lt;Function&gt; cons = Local&lt;Function&gt;::New(isolate, constructor);
  Local&lt;Context&gt; context = isolate-&gt;GetCurrentContext();
  Local&lt;Object&gt; instance =
      cons-&gt;NewInstance(context, argc, argv).ToLocalChecked();

  args.GetReturnValue().Set(instance);
}

}  // namespace demo
</code></pre>
<p>Test it with:</p>
<pre><code class="lang-js">// test.js
const addon = require(&#39;./build/Release/addon&#39;);

const obj1 = addon.createObject(10);
const obj2 = addon.createObject(20);
const result = addon.add(obj1, obj2);

console.log(result);
// Prints: 30
</code></pre>
<h3>AtExit hooks<span><a class="mark" href="#addons_atexit_hooks" id="addons_atexit_hooks">#</a></span></h3>
<p>An &quot;AtExit&quot; hook is a function that is invoked after the Node.js event loop
has ended but before the JavaScript VM is terminated and Node.js shuts down.
&quot;AtExit&quot; hooks are registered using the <code>node::AtExit</code> API.</p>
<h4>void AtExit(callback, args)<span><a class="mark" href="#addons_void_atexit_callback_args" id="addons_void_atexit_callback_args">#</a></span></h4>
<div class="signature"><ul>
<li><code>callback</code>: <code>void (*)(void*)</code> - A pointer to the function to call at exit.</li>
<li><code>args</code>: <code>void*</code> - A pointer to pass to the callback at exit.</li>
</ul>
</div><p>Registers exit hooks that run after the event loop has ended but before the VM
is killed.</p>
<p>AtExit takes two parameters: a pointer to a callback function to run at exit,
and a pointer to untyped context data to be passed to that callback.</p>
<p>Callbacks are run in last-in first-out order.</p>
<p>The following <code>addon.cc</code> implements AtExit:</p>
<pre><code class="lang-cpp">// addon.cc
#undef NDEBUG
#include &lt;assert.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;node.h&gt;

namespace demo {

using node::AtExit;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;

static char cookie[] = &quot;yum yum&quot;;
static int at_exit_cb1_called = 0;
static int at_exit_cb2_called = 0;

static void at_exit_cb1(void* arg) {
  Isolate* isolate = static_cast&lt;Isolate*&gt;(arg);
  HandleScope scope(isolate);
  Local&lt;Object&gt; obj = Object::New(isolate);
  assert(!obj.IsEmpty()); // assert VM is still alive
  assert(obj-&gt;IsObject());
  at_exit_cb1_called++;
}

static void at_exit_cb2(void* arg) {
  assert(arg == static_cast&lt;void*&gt;(cookie));
  at_exit_cb2_called++;
}

static void sanity_check(void*) {
  assert(at_exit_cb1_called == 1);
  assert(at_exit_cb2_called == 2);
}

void init(Local&lt;Object&gt; exports) {
  AtExit(sanity_check);
  AtExit(at_exit_cb2, cookie);
  AtExit(at_exit_cb2, cookie);
  AtExit(at_exit_cb1, exports-&gt;GetIsolate());
}

NODE_MODULE(addon, init);

}  // namespace demo
</code></pre>
<p>Test in JavaScript by running:</p>
<pre><code class="lang-js">// test.js
const addon = require(&#39;./build/Release/addon&#39;);
</code></pre>

      </div>
    </div>
  </div>
  <script src="assets/sh_main.js"></script>
  <script src="assets/sh_javascript.min.js"></script>
  <script>highlight(undefined, undefined, 'pre');</script>
</body>
</html>

